<?php
class Session_Middleware {
    protected $func;

    public function __construct($func) {
        $this->func = $func;
    }

    public function __invoke(\Swoole\Http\Request $request, \Swoole\Http\Response $response) {
		$config = Yaf_Registry::get('Config');
		$sessionName = session_name();
		if (isset($request->cookie[$sessionName])) {
			$sessionId = $request->cookie[$sessionName];
		} else {
			$sessionId = Session::generateSessId();
			$request->cookie[$sessionName] = $sessionId;
		}
		Session::setSessId($sessionId);
		Session::init();
		
        $cookie = session_get_cookie_params();
        $lifetime = time() + $config->session->lifetime;
        $response->cookie($sessionName, $sessionId, $lifetime, $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly']);
        
		call_user_func($this->func, $request, $response);
    }
}
